import { createRouter, createWebHistory } from 'vue-router';
import type {
  Router,
  RouteRecordRaw,
  NavigationGuardNext,
  RouteLocationNormalized,
} from 'vue-router';
import routerUtil from '../util/Util.ts';
import Register from '../components/Login/compent/Register.vue';
import Login from '../components/Login/compent/Login.vue';
import MenuManager from '../components/manager/menuManager/menuManager.vue';
import managerMain from '../components/manager/main.vue';
const Index = () => import('../components/Index/index.vue');
const UserLogin = () => import('../components/Login/UserLogin.vue');
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/index',
    meta: { requiresAuth: true },
  },
  {
    path: '/index',
    name: 'Index',
    component: Index,
    meta: { requiresAuth: true },
  },
  {
    path: '/userLogin',
    name: 'userLogin',
    component: UserLogin,
    meta: { requiresAuth: false },
    children: [
      {
        path: 'register',
        name: 'Register',
        component: Register,
        meta: { requiresAuth: false },
      },
      {
        path: 'login',
        name: 'Login',
        component: Login,
        meta: { requiresAuth: false },
      },
    ],
  },
  {
    path: '/manager',
    name: 'ManagerMain',
    component: managerMain,
    meta: { requiresAuth: true },
    children: [
      {
        path: 'menu-manager',
        name: 'menuManager',
        component: MenuManager,
        meta: { requiresAuth: false },
      },
    ],
  },
];
const router: Router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes,
});

router.beforeEach(
  async (
    to: RouteLocationNormalized,
    _from: RouteLocationNormalized,
    next: NavigationGuardNext
  ) => {
    const token = routerUtil.getToken();
    const isVailToken = routerUtil.isVailToken(token);
    const isNeedAuth = to.meta.requiresAuth === true;
    if (isNeedAuth) {
      isVailToken
        ? next()
        : next({
            path: './userLogin/login',
            query: { redirect: to.fullPath },
          });
    } else {
      isVailToken && to.fullPath === './userLogin/login' ? next('./index') : next();
    }
  }
);

export default router;
